package com.heima.comment.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.comment.pojos.ApComment;
import com.heima.comment.pojos.ApCommentRepay;
import com.heima.comment.pojos.ApCommentRepayLike;
import com.heima.comment.pojos.CommentRepayVo;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.constants.ApCommentConstants;
import com.heima.feign.user.IUserClient;
import com.heima.feign.wemedia.IWemediaClient;
import com.heima.model.comment.dtos.CommentRepayDto;
import com.heima.model.comment.dtos.CommentRepayLikeDto;
import com.heima.model.comment.dtos.CommentRepaySaveDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApUserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.KafkaClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: Tangguo
 * @Date: 2023-06-28  15:31
 */
@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {

    @Autowired
    private IUserClient userClient;

    @Autowired
    private IWemediaClient wemediaClient;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    /**
     * 保存评论回复
     *
     * @param dto :
     * @return ResponseResult
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {
        //1.参数校验
        if (dto == null || dto.getCommentId() == null || StringUtils.isBlank(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.判断用户是否登录
        ApUser user = ApUserThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN, "当前你还未登录，请登录后操作");
        }
        //3.评论内容不能超过140字
        if (dto.getContent().length() >= 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "评论内容不能超过140字");
        }
        //4.评论内容需要做文本垃圾检测
        //调用文章纯文本敏感词审核
        boolean result = wemediaClient.isTextScanOk(dto.getContent());
        if (!result) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_COMMENT_TEXT_SCAN_FAIL, "评论内容含有敏感词");
        }

        //5.封装实体类
        ApUser dbUser = userClient.findUserById(user.getId());
        if (dbUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN, "登录信息有误");
        }
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(user.getId());
        apCommentRepay.setAuthorName(dbUser.getName());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setLikes(0);
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());

        //5.1调用mongodb保存评论回复
        mongoTemplate.save(apCommentRepay);

        //6.保存成功后需要更新评论的回复数量
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        apComment.setReply(apComment.getReply() + 1);
        //6.1调用mongodb保存评论
        mongoTemplate.save(apComment);

        //7.调用kafka更新article微服务ap_article数据库表comment字段
        //7.1先查询到当前文章id
        Map map = new HashMap();
        map.put("articleId", apComment.getEntryId());
        map.put("add", 1);

        kafkaTemplate.send(ApCommentConstants.AP_COMMENT_SYNC_ARTICLE, JSON.toJSONString(map));


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询评论回复列表
     *
     * @param dto :
     * @return ResponseResult
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto dto) {
        //1.参数校验
        if (dto == null || dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询评论列表，根据当前文章进行检索，按照创建时间倒序，分页查询（默认10条数据）
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("createdTime").lt(dto.getMinDate()));
        query.with(Sort.by(Sort.Direction.DESC, "createdTime")).limit(10);
        List<ApCommentRepay> commentRepayList = mongoTemplate.find(query, ApCommentRepay.class);

        //3.判断用户是否登录
        ApUser user = ApUserThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN, "当前未登录，请登录后再操作");
        }
        //4.如果当天登录人点赞了某条评论，需要高亮展示 点赞按钮
        List<String> idList = commentRepayList.stream().map(commentRepay -> commentRepay.getId()).collect(Collectors.toList());
        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(Query.query(Criteria.where("commentRepayId").in(idList).and("authorId").is(user.getId())), ApCommentRepayLike.class);

        if (apCommentRepayLikes == null || apCommentRepayLikes.size() == 0) {
            return ResponseResult.okResult(commentRepayList);
        }

        List<CommentRepayVo> arrayList = new ArrayList<>();
        commentRepayList.forEach(x -> {
            CommentRepayVo commentRepayVo = new CommentRepayVo();
            BeanUtils.copyProperties(x, commentRepayVo);
            for (ApCommentRepayLike apCommentRepayLike : apCommentRepayLikes) {
                if (x.getId().equals(apCommentRepayLike.getCommentRepayId())) {
                    commentRepayVo.setOperation((short) 0);
                    break;
                }
            }

            arrayList.add(commentRepayVo);

        });

        return ResponseResult.okResult(arrayList);

    }

    /**
     * 点赞
     *
     * @param dto :
     * @return ResponseResult
     */
    @Override
    public ResponseResult likeCommentRepay(CommentRepayLikeDto dto) {
        //1.参数校验
        if (dto == null || dto.getCommentRepayId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.判断用户是否登录
        ApUser user = ApUserThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN, "当前你还未登录，请登录后操作");
        }
        //3.用户对评论回复点赞
        ApCommentRepay apCommentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        if (apCommentRepay != null && dto.getOperation() == 0) {
            //查询是否已经对当前评论点赞
            ApCommentRepayLike dbApRepayLike = mongoTemplate.findOne(Query.query(Criteria.where("commentRepayId").is(dto.getCommentRepayId()).and("authorId")
                    .is(user.getId())), ApCommentRepayLike.class);
            if (dbApRepayLike != null) {
                apCommentRepay.setLikes(1);
                mongoTemplate.save(apCommentRepay);
            } else {
                //3.1增加点赞数量
                apCommentRepay.setLikes(apCommentRepay.getLikes() + 1);
                //3.2调用mogodb保存评论回复
                mongoTemplate.save(apCommentRepay);

                //3.3保存当前用户对于当前评论的数据记录
                ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
                apCommentRepayLike.setCommentRepayId(apCommentRepay.getId());
                apCommentRepayLike.setAuthorId(user.getId());
                apCommentRepayLike.setOperation((short) 0);

                //3.2调用mogodb保存评论回复点赞
                mongoTemplate.save(apCommentRepayLike);
            }
        } else {
            //更新点赞数据
            int num = apCommentRepay.getLikes() - 1;
            if(num<0){
                apCommentRepay.setLikes(0);
            }else {
                apCommentRepay.setLikes(num);
            }
            mongoTemplate.save(apCommentRepay);

            Query query = Query.query(Criteria.where("commentRepayId").is(apCommentRepay.getId()).and("authorId").is(user.getId()));
            mongoTemplate.remove(query, ApCommentRepayLike.class);
        }

        //4.用户取消点赞
        Map<String, Object> result = new HashMap<>();
        result.put("likes", apCommentRepay.getLikes());
        return ResponseResult.okResult(result);

    }
}
